{% extends 'base.html' %}

{% block title %}编辑燃料到厂记录 - 燃料结算系统{% endblock %}

{% block page_title %}编辑燃料到厂记录{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-body">
                <form method="POST" id="arrivalForm">
                    {{ form.hidden_tag() }}
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="form-group">
                                {{ form.arrival_date.label(class="form-label") }}
                                {{ form.arrival_date(class="form-control", type="month") }}
                                {% if form.arrival_date.errors %}
                                <div class="invalid-feedback d-block">
                                    {% for error in form.arrival_date.errors %}
                                    <span>{{ error }}</span>
                                    {% endfor %}
                                </div>
                                {% endif %}
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                {{ form.fuel_contract_id.label(class="form-label") }}
                                {{ form.fuel_contract_id(class="form-select") }}
                                {% if form.fuel_contract_id.errors %}
                                <div class="invalid-feedback d-block">
                                    {% for error in form.fuel_contract_id.errors %}
                                    <span>{{ error }}</span>
                                    {% endfor %}
                                </div>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="form-group">
                                {{ form.arrival_quantity.label(class="form-label") }}
                                {{ form.arrival_quantity(class="form-control", type="number", step="0.01") }}
                                {% if form.arrival_quantity.errors %}
                                <div class="invalid-feedback d-block">
                                    {% for error in form.arrival_quantity.errors %}
                                    <span>{{ error }}</span>
                                    {% endfor %}
                                </div>
                                {% endif %}
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                {{ form.arrival_calorific_value.label(class="form-label") }}
                                {{ form.arrival_calorific_value(class="form-control", type="number", step="0.01") }}
                                {% if form.arrival_calorific_value.errors %}
                                <div class="invalid-feedback d-block">
                                    {% for error in form.arrival_calorific_value.errors %}
                                    <span>{{ error }}</span>
                                    {% endfor %}
                                </div>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="form-group">
                                {{ form.transport_type.label(class="form-label") }}
                                {{ form.transport_type(class="form-select") }}
                                {% if form.transport_type.errors %}
                                <div class="invalid-feedback d-block">
                                    {% for error in form.transport_type.errors %}
                                    <span>{{ error }}</span>
                                    {% endfor %}
                                </div>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label class="form-label">合同类型</label>
                                <input type="text" id="contractType" class="form-control" readonly>
                            </div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">到厂标煤量 (预览)</label>
                                <input type="text" id="standardCoal" class="form-control" readonly value="{{ "{:.2f}".format(arrival.arrival_standard_coal) }}">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">矿发数量估算 (预览)</label>
                                <input type="text" id="estimatedMineQuantity" class="form-control" readonly value="{{ "{:.2f}".format(arrival.estimated_mine_quantity) }}">
                            </div>
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">矿发单价估算 (预览)</label>
                                <input type="text" id="estimatedMineUnitPrice" class="form-control" readonly value="{{ "{:.2f}".format(arrival.estimated_mine_unit_price) }}">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="form-label">入厂标单 (预览)</label>
                                <input type="text" id="arrivalStandardUnitPrice" class="form-control" readonly value="{{ "{:.2f}".format(arrival.arrival_standard_unit_price) }}">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="d-flex justify-content-between">
                                <a href="{{ url_for('arrivals.index') }}" class="btn btn-secondary">
                                    <i class="bi bi-arrow-left me-2"></i>返回
                                </a>
                                {{ form.submit(class="btn btn-primary") }}
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const fuelContractId = document.getElementById('fuel_contract_id');
        const arrivalQuantity = document.getElementById('arrival_quantity');
        const arrivalCalorificValue = document.getElementById('arrival_calorific_value');
        const transportType = document.getElementById('transport_type');
        
        const contractType = document.getElementById('contractType');
        const standardCoal = document.getElementById('standardCoal');
        const estimatedMineQuantity = document.getElementById('estimatedMineQuantity');
        const estimatedMineUnitPrice = document.getElementById('estimatedMineUnitPrice');
        const arrivalStandardUnitPrice = document.getElementById('arrivalStandardUnitPrice');
        
        // 获取合同详情
        function getContractDetails() {
            const contractId = fuelContractId.value;
            if (!contractId) {
                contractType.value = '';
                return;
            }
            
            fetch(`/arrivals/get_contract_details/${contractId}`)
                .then(response => response.json())
                .then(data => {
                    contractType.value = data.contract_type;
                    calculateValues();
                })
                .catch(error => {
                    console.error('获取合同详情失败:', error);
                });
        }
        
        // 计算预览值
        function calculateValues() {
            const quantity = parseFloat(arrivalQuantity.value) || 0;
            const calorificValue = parseFloat(arrivalCalorificValue.value) || 0;
            const type = transportType.value;
            const cType = contractType.value;
            
            // 计算到厂标煤量
            const stdCoal = quantity * calorificValue / 7000;
            standardCoal.value = stdCoal.toFixed(2);
            
            // 计算矿发数量估算
            let estMineQuantity = 0;
            if (type === '汽运') {
                estMineQuantity = quantity / 0.99;
            } else if (type === '火车短倒') {
                estMineQuantity = quantity / 0.98;
            } else if (type === '火车直发') {
                estMineQuantity = quantity / 0.985;
            }
            estimatedMineQuantity.value = estMineQuantity.toFixed(2);
            
            // 计算矿发单价估算
            let estMineUnitPrice = 0;
            const estCalorificValue = calorificValue + 100;
            
            if (cType === '集团煤') {
                if (estCalorificValue >= 4300) {
                    estMineUnitPrice = 570 / 5500 * estCalorificValue;
                } else if (estCalorificValue >= 3800) {
                    estMineUnitPrice = 0.0806 * estCalorificValue;
                } else if (estCalorificValue >= 3300) {
                    estMineUnitPrice = 0.0706 * estCalorificValue;
                } else if (estCalorificValue >= 2500) {
                    estMineUnitPrice = 0.0676 * estCalorificValue;
                } else {
                    estMineUnitPrice = 0.02 * estCalorificValue;
                }
            }
            
            estimatedMineUnitPrice.value = estMineUnitPrice.toFixed(2);
            
            // 入厂标单预览 (简化计算)
            if (stdCoal > 0) {
                const arrivalValue = estMineQuantity * estMineUnitPrice / 1.13;
                const arrivalStdUnitPrice = arrivalValue / stdCoal;
                arrivalStandardUnitPrice.value = arrivalStdUnitPrice.toFixed(2);
            } else {
                arrivalStandardUnitPrice.value = '0.00';
            }
        }
        
        // 事件监听
        fuelContractId.addEventListener('change', getContractDetails);
        arrivalQuantity.addEventListener('input', calculateValues);
        arrivalCalorificValue.addEventListener('input', calculateValues);
        transportType.addEventListener('change', calculateValues);
        
        // 表单提交前验证
        document.getElementById('arrivalForm').addEventListener('submit', function(event) {
            const requiredFields = [
                { field: fuelContractId, name: '燃料合同' },
                { field: arrivalQuantity, name: '到厂数量' },
                { field: arrivalCalorificValue, name: '到厂热值' },
                { field: transportType, name: '拉运类型' }
            ];
            
            let isValid = true;
            
            requiredFields.forEach(item => {
                if (!item.field.value) {
                    alert(`请填写${item.name}`);
                    item.field.focus();
                    isValid = false;
                    event.preventDefault();
                    return false;
                }
            });
            
            return isValid;
        });
        
        // 初始化
        if (fuelContractId.value) {
            getContractDetails();
        }
    });
</script>
{% endblock %} 